package com.xp.gather2.comment.utils;

import com.google.common.collect.Maps;
import com.xp.gather2.exception.FileException;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.Random;

/**
 * 文件操作工具类
 *
 * @作者 wangym
 * @创建日期 Aug 18, 2012 10:06:10 AM
 * @版本 V 1.0
 */
public class FileUtil {

    /**
     * 上传文件.
     *
     * @param file     上传的文件
     * @param realPath 文件上传的真实路径
     * @param path     文件相对路径
     * @return map{fileName:文件名称，filePath:文件路径}
     * @throws Exception
     * @author bulang
     */
    public static Map<String, String> upload(MultipartFile file, String realPath, String path) throws Exception {

        try {
            // 验证文件是不是空
            if (file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
                throw new FileException("上传文件为空！");
            }

            String filepath = realPath + path;


            // 创建保存文件的目录
            File filedirectory = new File(filepath);
            if (!filedirectory.exists() && !filedirectory.isDirectory()) {
                filedirectory.mkdirs();
            }
            // 生成文件名，年月日+4位流水号
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name = "";
            String dateString = DateUtils.getCurrentDateFormat("yyyyMMddHHmmssSSS");
            int i = 0;

            while (true) {
                name = dateString + getRandomNumString(2) + NumberUtils.formSeq(i, 6) + suffix;
                if (new File(filepath + name).exists()) {
                    i++;
                } else {
                    break;
                }
            }
            // 生成本地文件
            File localFile = new File(filepath + name);
            if (localFile.exists()) {
                while (true) {
                    name = dateString + getRandomNumString(2) + NumberUtils.formSeq(i, 6) + suffix;
                    if (new File(filepath + name).exists()) {
                        i++;
                    } else {
                        break;
                    }
                }
                localFile = new File(filepath + name);
            }
            file.transferTo(localFile);

            Map<String, String> fileData = Maps.newHashMap();
            fileData.put("fileName", file.getOriginalFilename());
            fileData.put("filePath", path + name);

            return fileData;
        } catch (Exception e) {
            e.printStackTrace();
            throw new FileException("上传文件失败！");
        }
    }

    /**
     * 上传文件.
     *
     * @param file     上传的文件
     * @param realPath 文件上传的真实路径
     * @param path     文件相对路径
     * @return map{fileName:文件名称，filePath:文件路径}
     * @throws Exception
     * @author bulang
     */
    public static Map<String, String> upload(MultipartFile file, String realPath, String path, String prefix) throws Exception {

        try {
            // 验证文件是不是空
            if (file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
                throw new FileException("上传文件为空！");
            }

            String filepath = realPath + path;


            // 创建保存文件的目录
            File filedirectory = new File(filepath);
            if (!filedirectory.exists() && !filedirectory.isDirectory()) {
                filedirectory.mkdirs();
            }
            // 生成文件名，年月日+4位流水号
            String fileName = file.getOriginalFilename();
            String suffix = "";
            if (fileName.split("\\.").length > 1) {
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            String name = "";
            String dateString = DateUtils.getCurrentDateFormat("yyyyMMddHHmmssSSS");
            int i = 0;

            while (true) {
                name = prefix + dateString + NumberUtils.formSeq(i, 9) + suffix;
                if (new File(filepath + name).exists()) {
                    i++;
                } else {
                    break;
                }
            }
            // 生成本地文件
            File localFile = new File(filepath + name);
            if (localFile.exists()) {
                while (true) {
                    name = prefix + dateString + NumberUtils.formSeq(i, 9) + suffix;
                    if (new File(filepath + name).exists()) {
                        i++;
                    } else {
                        break;
                    }
                }
                localFile = new File(filepath + name);
            }
            file.transferTo(localFile);

            Map<String, String> fileData = Maps.newHashMap();
            fileData.put("fileName", file.getOriginalFilename());
            fileData.put("filePath", path + name);

            return fileData;
        } catch (Exception e) {
            e.printStackTrace();
            throw new FileException("上传文件失败！");
        }
    }

    public static String getRandomNumString(int length) { //length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String getRandomString(int length) { // length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * @param response
     * @param path
     * @param name
     * @author bulang
     */
    public static void download(HttpServletResponse response, String path, String name) throws Exception {

        BufferedInputStream dis = null;
        BufferedOutputStream fos = null;

        try {

            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            String fName = new String(name.getBytes("gb2312"), "ISO-8859-1");

            String suffix = path.substring(path.lastIndexOf("."));
            fName = fName + suffix;
            response.addHeader("Content-Disposition", "attachment;filename=" + fName);
            response.setHeader("Content-Length", String.valueOf(new File(path).length()));

            dis = new BufferedInputStream(new FileInputStream(path));
            fos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[2048];
            int bytesRead;

            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
                fos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dis != null) {
                dis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }



    /**
     * 文件删除
     *
     * @param path
     * @author wangym
     * @date Aug 18, 2012 10:16:13 AM
     */
    public static void deleteFile(String path) {
        if (StringUtil.IsNotNull(path)) {//path不为空
            path = StringUtil.getWebRootPath() + path;
            File file = new File(path);
            file.deleteOnExit();
        }
    }


    /***
     * 读取Txt文件
     * @param content
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean writeTxtFile(String content, String path, String fileName) throws Exception {
        File file = new File(path + File.separator + fileName);
        File filedirectory = new File(path);
        if (!filedirectory.exists() && !filedirectory.isDirectory()) {
            filedirectory.mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        RandomAccessFile mm = null;
        boolean flag = false;
        FileOutputStream o = null;
        try {
            o = new FileOutputStream(path + File.separator + fileName);
            o.write(content.getBytes("GBK"));
            o.close();
            //   mm=new RandomAccessFile(fileName,"rw");
            //   mm.writeBytes(content);
            flag = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            if (mm != null) {
                mm.close();
            }
        }
        return flag;
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     *
     * @param fileName 文件名
     */
    public static String readFileByLines(String fileName) {
        StringBuilder sb = new StringBuilder();
        sb.append("");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileName)),
                    "GBK"));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                sb = sb.append(tempString);
                sb.append("\n");
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return sb.toString();
    }


}
